package com.haoyun.mirage.gateway.handler;

import com.alibaba.fastjson.JSON;
import com.haoyun.common.constant.CommonConstant;
import com.haoyun.common.core.Result;
import com.haoyun.common.core.http.BaseHttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 */
@Slf4j
@Component
public class RequestAccessDeniedHandler extends OAuth2AccessDeniedHandler {
    private static final String DEFAULT_ERROR_MESSAGE = "授权失败，禁止访问！";

    /**
     * 授权拒绝处理
     *
     * @param request       request
     * @param response      response
     * @param authException authException
     * @throws IOException      IOException
     * @throws ServletException ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
        log.info("授权失败，禁止访问 {}", request.getRequestURI());
        response.setCharacterEncoding(CommonConstant.UTF8);
        response.setStatus(BaseHttpStatus.SC_UNAUTHORIZED);
        response.setContentType(CommonConstant.CONTENT_TYPE);
        PrintWriter printWriter = response.getWriter();
        printWriter.write(JSON.toJSONString(Result.buildErrorResult(BaseHttpStatus.SC_UNAUTHORIZED, DEFAULT_ERROR_MESSAGE)));
    }
}
